/* $RCSFile: Global.asax.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/Global.asax.cs $
 * $log$
 * Revision 71 2011/02/22 01:23:08  christian.surieux
 *   V4 Migration 22/2/11
 * Revision 71 2011/02/22 01:22:07  christian.surieux
 *   V4 Migration 22/2/11
 * Revision 48 2011/01/27 09:39:42  christian.surieux
 *   Suppress lock on CRMWrapper create and start
 * Revision 20 2010/08/10 17:55:42  christian.surieux
 *   Missing comments in asax asmx ashx files
 * Revision 19 2010/08/09 09:43:41  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Net;
using System.Diagnostics;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Configuration;
using System.ComponentModel;
using System.Web;
using System.Web.Configuration;
using System.Web.Caching;
using System.Security;
using System.Security.Principal;
using System.Reflection;
using System.Web.Security;
using System.Data.SqlClient;
using System.Threading;
using System.Globalization;
using System.Security.Permissions;

using Trace2    =   System.Diagnostics.Trace;

using AddonNice.Design;
using AddonNice.BLL.Utils;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Core;
using AddonNice.Authentication;
using AddonNice.CRMWrapper;

namespace AddonNice
{
	public partial class Global : HttpApplication
	{
		const string strRefreshed       =   "refreshed";
		// Object doing Application based initializations, needs to be static to be seen by all portals running this Application
		// but called only one time because it initialize some delegates that should exist as singletons
		static InitApplication InitApp	=	null;
		
		/// <summary>
		/// Application_BeginRequest Event
		///
		/// The Application_BeginRequest method is an ASP.NET event that executes 
		/// on each web request into the portal application.  The below method
		/// obtains the current PageID from the querystring of the 
		/// request -- and then obtains the configuration necessary to process
		/// and render the request.
		///
		/// This portal configuration is stored within the application's "Context"
		/// object -- which is available to all pages, controls and components
		/// during the processing of a single request.
		/// 
		/// You can change portals via querystring according an option from web.config:
		/// IgnoreFirstDomain (boolean): if true the trailing domain is ignored
		/// if false the full domain is considered.
		/// </summary>
		protected void Application_BeginRequest(Object sender, EventArgs e) 
		{
			if (AuthenticationTrace.Sw.TraceVerbose)
			{
				Trace2.WriteLine("[V]Global Application_BeginRequest BEG.",AuthenticationTrace.Sw.Info);
				/* Pb IIS7
				if ( Request.LogonUserIdentity != null )
					Trace2.WriteLine(
						string.Format("[V]Global Application_BeginRequest User: {0}, Name: {1}",
										Request.LogonUserIdentity.User,Request.LogonUserIdentity.Name), AuthenticationTrace.Sw.Info);
				 */
			}
			// Needed as far as App is running under IIS7 in IP mode
			if ( InitApp.StartWithContext(Context) )
			{
				if (AuthenticationTrace.Sw.TraceVerbose)
					Trace2.WriteLine( "[V]Global Application_BeginRequest Installing Authenticating handlers.",AuthenticationTrace.Sw.Info);
				System.Web.ApplicationServices.AuthenticationService.Authenticating += 
							new EventHandler<System.Web.ApplicationServices.AuthenticatingEventArgs>(AuthenticationService_Authenticating);
				System.Web.ApplicationServices.AuthenticationService.CreatingCookie 
						+= new EventHandler<System.Web.ApplicationServices.CreatingCookieEventArgs>(AuthenticationService_CreatingCookie);
			}
			
			// 1st Check: is it a dangerously malformed request?
			// Important patch http://support.microsoft.com/?kbid=887459
			if (Context.Request.Path.IndexOf('\\') >= 0 || 
				System.IO.Path.GetFullPath(Context.Request.PhysicalPath) != Context.Request.PhysicalPath)
			{
				if ( GlobalTraceSwitch.Sw.TraceError )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Global Application_BeginRequest Malformed request Path: {0}", Context.Request.Path),GlobalTraceSwitch.Sw.Info);
				throw new ADNCRMRedirect(InternalLogLevel.Warn, HttpStatusCode.NotFound, "Malformed request", null);
				}
	
			// 2nd Check: is the AllPortals Lock switched on?
			// let the user through if client IP address is in LockExceptions list, otherwise throw...
			string _rawUrl                          =   Context.Request.RawUrl.ToLower(CultureInfo.InvariantCulture);
			bool LockAllPortals                     =   Config.LockAllPortals;
			if (GlobalTraceSwitch.Sw.TraceVerbose)
			{
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_BeginRequest _rawUrl: {0}", _rawUrl), GlobalTraceSwitch.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_BeginRequest Url: {0}", Context.Request.Url), GlobalTraceSwitch.Sw.Info);
				if ( Context.Request.UrlReferrer != null )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_BeginRequest UrlReferrer: {0}", Context.Request.UrlReferrer), GlobalTraceSwitch.Sw.Info);
				if ( ( Context.Request.UserLanguages != null )  && Context.Request.UserLanguages.Length > 0 )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_BeginRequest Context.Request.UserLanguages[0]: {0}", Context.Request.UserLanguages[0]), GlobalTraceSwitch.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_BeginRequest LockAllPortals: {0}", LockAllPortals), GlobalTraceSwitch.Sw.Info);
			}
			if (LockAllPortals)
			{
				string _lockRedirect                    =   Config.LockRedirect;
				if (!_rawUrl.EndsWith(_lockRedirect))
				{
					// construct IPList
					string[] lockKeyHolders             =   Config.LockKeyHolders.Split(new char[] { ';' },StringSplitOptions.RemoveEmptyEntries);
					IPList ipList                       =   new IPList();
					foreach (string lockKeyHolder in lockKeyHolders)
					{
						if (lockKeyHolder.IndexOf("-") > -1)
							ipList.AddRange(lockKeyHolder.Substring(0, lockKeyHolder.IndexOf("-")), lockKeyHolder.Substring(lockKeyHolder.IndexOf("-") + 1));
						else
							ipList.Add(lockKeyHolder);
					}
					// check if requestor's IP address is in allowed list
					if (!ipList.CheckNumber(Context.Request.UserHostAddress))
						throw new PortalsLockedException();
				}
			}

			// 3rd check, if img, css or http handler for resource extension don't continue.
			if ( DoNotLoadPortal )
			{
				if ( GlobalTraceSwitch.Sw.TraceVerbose )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_BeginRequest exiting _rawUrl: {0}", _rawUrl),GlobalTraceSwitch.Sw.Info);
				return;
			}

			// 4th Check: is database/code version correct?
#if DEBUG
			int versionDelta = 0;
#else
			int versionDelta                    =   DatabaseDB.DatabaseVersion.CompareTo(PortalSettings.CodeVersion);
#endif
			// if DB and code versions do not match
			if ( versionDelta != 0 )
			{
				Uri _requestUri                 =   Context.Request.Url;
				string _databaseUpdateRedirect  =   Config.DatabaseUpdateRedirect;
				if (_databaseUpdateRedirect.StartsWith("~/"))
					_databaseUpdateRedirect     =   _databaseUpdateRedirect.TrimStart(new char[] { '~' });
				if (!_requestUri.AbsolutePath.ToLower(CultureInfo.InvariantCulture).EndsWith(_databaseUpdateRedirect.ToLower(CultureInfo.InvariantCulture)))
				{
					// ...and this is not DB Update page
					string errorMessage         =   string.Format("DatabaseDB version: {0} / Code version: {1}",DatabaseDB.DatabaseVersion,Portal.CodeVersion);
					if ( versionDelta < 0 ) // DB Version is behind Code Version
						throw new DatabaseVersionException(errorMessage);
					else // DB version is ahead of Code Version
						throw new CodeVersionException(errorMessage);
				}
				// this is already DB Update page... 
				else    return; // so skip creation of PortalSettings
			}

			// ************ 'calculate' response to this request ************
			//
			// Test 1 - try requested Alias and requested PageID
			// Test 2 - try requested Alias and PageID 0
			// Test 3 - try default Alias and requested PageID
			// Test 4 - try default Alias and PageID 0
			//
			// The UrlToleranceLevel determines how many times the test is allowed to fail before the request is considered
			// to be "an error" and is therefore redirected:
			//
			// UrlToleranceLevel 1 
			//		- requested Alias must be valid - if invalid, InvalidAliasRedirect page on default portal will be shown
			//		- if requested PageID is found, it is shown
			//		- if requested PageID is not found, InvalidPageIdRedirect page is shown
			// 
			// UrlToleranceLevel 2 
			//		- requested Alias must be valid - if invalid, InvalidAliasRedirect page on default portal will be shown
			//		- if requested PageID is found, it is shown
			//		- if requested PageID is not found, PageID 0 (Home page) is shown
			//
			// UrlToleranceLevel 3 
			//		- if requested Alias is invalid, default Alias will be used
			//		- if requested PageID is found, it is shown
			//		- if requested PageID is not found, InvalidPageIdRedirect page is shown
			// 
			// UrlToleranceLevel 4 - 
			//		- if requested Alias is invalid, default Alias will be used
			//		- if requested PageID is found, it is shown
			//		- if requested PageID is not found, PageID 0 (Home page) is shown

			PortalSettings portalSettings       =   null;
			int pageID                          =   Portal.PageID; // Get PageID from QueryString
			string portalAlias                  =   Portal.UniqueID; // Get requested alias from querystring, cookies or hostname
			string defaultAlias                 =   Config.DefaultPortal; // get default portal from config
			if ( string.IsNullOrEmpty(portalAlias) ) // avoid search for portalAlias empty
				portalAlias                     =   defaultAlias;

			// load arrays with values to test
			string[] testAlias                  =   new string[4] { portalAlias, portalAlias, defaultAlias, defaultAlias };
			int[] testPageID                    =   new int[4] { pageID, StStr.PageIDNotAssigned, pageID, StStr.PageIDNotAssigned };

			int testsAllowed                    =   Config.UrlToleranceLevel;
			int testsToRun                      =   testsAllowed > 2 ? 4 : 2;
			// if requested alias is default alias, limit UrlToleranceLevel to max value of 2 and limit tests to 2
			if ( portalAlias == defaultAlias)
			{
				testsAllowed                    =   testsAllowed % 2;
				testsToRun                      =   2;
				if ( pageID == StStr.PageIDNotAssigned )
					testsToRun                  =   1;
			}

			int testsCounter                    =   1;
			bool Ok                             =   false;
			while (!Ok && testsCounter <= testsToRun)
			{
				if (GlobalTraceSwitch.Sw.TraceVerbose)
				{
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global PortalSettings trying TestCounter: {0}- TestsToRun: {1}", testsCounter, testsToRun), GlobalTraceSwitch.Sw.Info);
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global PortalSettings trying PortalAlias {0}- PageID '{1}'", testAlias[testsCounter - 1], testPageID[testsCounter - 1]), GlobalTraceSwitch.Sw.Info);
				}
				//try with current values from arrays
				try
				{
					portalSettings              =   new PortalSettings(testPageID[testsCounter - 1], testAlias[testsCounter - 1]);
					Ok                          =   portalSettings.isLoaded;
				}
				catch (LicenseException lex)
				{
					string msg                  =   string.Format("[E]Global Application_BeginRequest licence Exception: {0}- redirecting request to ErrorNoLicense page.", lex);
					if ( GlobalTraceSwitch.Sw.TraceError )
						Trace2.WriteLine(msg,GlobalTraceSwitch.Sw.Info);
					// critical error - neither requested alias nor default alias could be found in DB
					throw new ADNCRMNoLicense(
						Config.NoLicenseErrorRedirect,
						InternalLogLevel.Fatal,
						Config.NoLicenseErrorResponse,
						msg,
						null);
				}
				// critical error - CRM Server unvailable
				catch (CRMWrapperException cex)
				{
					string msg                  =   string.Format("[E]Global Application_BeginRequest CRM Exception: {0}- redirecting request to ErrorCRM page.", cex);
					if ( GlobalTraceSwitch.Sw.TraceError )
						Trace2.WriteLine(msg,GlobalTraceSwitch.Sw.Info);
					throw new ADNCRMException(
						Config.CRMErrorRedirect,
						InternalLogLevel.Fatal,
						Config.CRMErrorResponse,
						msg,
						null);
				}
				// critical error - DB un reachable, unnecessary to loop
				catch (DatabaseUnreachableException ex)
				{
					if ( GlobalTraceSwitch.Sw.TraceError )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Global Application_BeginRequest Stopping process ex: {0}",ex),GlobalTraceSwitch.Sw.Info);
					throw;
				}
				catch (UnknownPortalAliasException)
				{
					if ( GlobalTraceSwitch.Sw.TraceError )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Global Application_BeginRequest UnknownPortalAliasException PortalAlias {0}- PageID '{1}'", testAlias[testsCounter - 1], testPageID[testsCounter - 1]),GlobalTraceSwitch.Sw.Info);
				}
				// any other exception we loop
				catch (Exception ex)
				{
					if ( GlobalTraceSwitch.Sw.TraceError )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Global Application_BeginRequest PortalSettings failed PortalAlias {0}- PageID '{1}', ex: {2}'", testAlias[testsCounter - 1], testPageID[testsCounter - 1], ex),GlobalTraceSwitch.Sw.Info);
				}
				testsCounter++; // increment the test counter and continue
			}

			if ( portalSettings == null || !portalSettings.isLoaded )
			{
				string msg  =   string.Format("[E]Global Application_BeginRequest Unable to load any portal from rawurl [{0}]- redirecting request to ErrorNoPortal page.",Context.Request.RawUrl);
				if ( GlobalTraceSwitch.Sw.TraceError )
					Trace2.WriteLine(msg,GlobalTraceSwitch.Sw.Info);
				// critical error - neither requested alias nor default alias could be found in DB
				throw new ADNCRMRedirect(Config.NoPortalErrorRedirect,InternalLogLevel.Fatal,Config.NoPortalErrorResponse,msg,null);
			}

			if ( Ok && ((testsCounter-1) <= testsAllowed) ) // success
			{
				if ( GlobalTraceSwitch.Sw.TraceVerbose )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_BeginRequest PortalSettings loaded for PortalAlias {0}- PageID '{1}', Counter: {2}'", testAlias[testsCounter - 2], testPageID[testsCounter - 2], testsCounter-1),GlobalTraceSwitch.Sw.Info);
				// Portal Settings has passed the test so add it to Context
				Context.Items.Add(StStr.strPortalSettings, portalSettings);
				Context.Items.Add(StStr.PortalID, portalSettings.PortalID);
				// Create the CRM Wrapper only when portal is successfully read
				PortalSecurity.CreateWrapper(portalSettings,portalSettings.CrmServer);
			}
			else // need to redirect
			{
				if ( portalSettings.PortalAlias != portalAlias ) // we didn't get the portal we asked for
				{
					string msg  =   string.Format("[E]Global Application_BeginRequest Invalid Alias [{0}] specified in request URL - redirecting (404) to InvalidAliasRedirect page.",portalAlias);
					if ( GlobalTraceSwitch.Sw.TraceError )
						Trace2.WriteLine(msg,GlobalTraceSwitch.Sw.Info);
					throw new ADNCRMRedirect(Config.InvalidAliasRedirect,InternalLogLevel.Info,HttpStatusCode.NotFound,msg,null);
				}

				if (portalSettings.ActivePageSettings.PageID != pageID) // we didn't get the page we asked for
				{
					string msg  =   string.Format("[E]Global Application_BeginRequest Invalid PageID [{0}] specified in request URL - redirecting (404) to InvalidPageIdRedirect page.",pageID);
					if ( GlobalTraceSwitch.Sw.TraceError )
						Trace2.WriteLine(msg,GlobalTraceSwitch.Sw.Info);
					throw new ADNCRMRedirect(Config.InvalidPageIdRedirect,InternalLogLevel.Info,HttpStatusCode.NotFound,msg,null);
				}
				else
				{
					string msg  =   string.Format("[E]Global Application_BeginRequest Unknown error tring to load from url [{0}] - redirecting (404) to InvalidPageIdRedirect page.",_rawUrl);
					if ( GlobalTraceSwitch.Sw.TraceError )
						Trace2.WriteLine(msg,GlobalTraceSwitch.Sw.Info);
					throw new ADNCRMRedirect(Config.InvalidPageIdRedirect,InternalLogLevel.Fatal,HttpStatusCode.NotFound,msg,null);
				}
			}


			// Try to get alias from cookie to determine if alias has been changed
			bool refreshSite                                    =   false;
			object obc                                          =   Context.Request.Cookies[StStr.DBPortalAlias];
			
			string oldAlias                                     =   string.Empty;
			if ( obc != null ) 
				oldAlias                                        =   ((HttpCookie)obc).Value.ToLower(CultureInfo.InvariantCulture);

			// Save portal Alias in a cookie
			Context.Response.Cookies[StStr.DBPortalAlias].Path  =   "/";
			Context.Response.Cookies[StStr.DBPortalAlias].Value =   portalSettings.BaseAlias;


			if (GlobalTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global PortalSettings testing for refresh UniqueID: '{0}' , oldAlias: '{1}'",  Portal.UniqueID, oldAlias), GlobalTraceSwitch.Sw.Info);
			if ( ( obc != null ) && ( oldAlias != Portal.UniqueID.ToLower(CultureInfo.InvariantCulture) ) )
				refreshSite                                     =   true; //Portal has changed since last page request
			// if switching portals then clean parameters
			// Must be the last instruction in this method 
			if (refreshSite) // this should be called only if Cookies enabled!
			{
				// Signout and force the browser to refresh only once to avoid any dead-lock
				if ( (Context.Request.Cookies[strRefreshed] == null )
					|| ( (Context.Request.Cookies[strRefreshed] != null )
						&& ( Context.Response.Cookies[strRefreshed].Value == StStr.strSmFalse) ) )
				{
					string rawUrl                                   =   Context.Request.RawUrl;

					Context.Response.Cookies[strRefreshed].Value    =   StStr.strSmTrue;
					Context.Response.Cookies[strRefreshed].Path     =   StStr.CookiePath; // "/"
					Context.Response.Cookies[strRefreshed].Expires  =   DateTime.Now.AddMinutes(1);

					// sign-out, if refreshed param on the command line we will not call it again
					PortalSecurity.SignOut(rawUrl, false);
				}
			}

			// invalidate cookie, so the page can be refreshed when needed
			if ( Context.Request.Cookies[strRefreshed] != null )
			{
				Context.Response.Cookies[strRefreshed].Path     =   StStr.CookiePath;
				Context.Response.Cookies[strRefreshed].Value    =   StStr.strSmFalse;
				Context.Response.Cookies[strRefreshed].Expires  =   DateTime.Now.AddMinutes(1);
			}
			if (GlobalTraceSwitch.Sw.TraceVerbose)
				Trace2.WriteLine( "[V]Global Application_BeginRequest END.", GlobalTraceSwitch.Sw.Info);
		}

		#region Methods dedicated to web services authentication

		void AuthenticationService_Authenticating(object sender, System.Web.ApplicationServices.AuthenticatingEventArgs e)
		{
			if (AuthenticationTrace.Sw.TraceVerbose)
			{
				Trace2.WriteLine( "[V]Global AuthenticationService_Authenticating BEG *******************************************************************", AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_Authenticating BEG Request.IsAuthenticated: {0}", Context.Request.IsAuthenticated), AuthenticationTrace.Sw.Info);
				/* Pb IIS7
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_Authenticating AuthenticationType: {0}", Context.Request.LogonUserIdentity.AuthenticationType), AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_Authenticating IsAnonymous: {0}", Context.Request.LogonUserIdentity.IsAnonymous), AuthenticationTrace.Sw.Info);
				try
				{
					Trace2.WriteLine(
						string.Format("[V]Global AuthenticationService_Authenticating User: {0}, Name: {1}",
																				Request.LogonUserIdentity.User,
																				Request.LogonUserIdentity.Name),AuthenticationTrace.Sw.Info);
					Trace2.WriteLine(
						string.Format("[V]Global AuthenticationService_Authenticating AuthenticationType: {0}, ImpersonationLevel: {1}",
																				Request.LogonUserIdentity.AuthenticationType,
																				Request.LogonUserIdentity.ImpersonationLevel),AuthenticationTrace.Sw.Info);
					Trace2.WriteLine(
						string.Format("[V]Global AuthenticationService_Authenticating IsAnonymous: {0}, IsGuest: {1}, IsSystem: {2}",
																				Request.LogonUserIdentity.IsAnonymous,
																				Request.LogonUserIdentity.IsGuest,
																				Request.LogonUserIdentity.IsSystem),AuthenticationTrace.Sw.Info);
					Trace2.WriteLine(
						string.Format("[V]Global AuthenticationService_Authenticating Owner: {0}, Token: {1}",
																				Request.LogonUserIdentity.Owner,
																				Request.LogonUserIdentity.Token),AuthenticationTrace.Sw.Info);
				}
				catch
				{}
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_Authenticating Context.User is null: {0}",Context.User == null ),AuthenticationTrace.Sw.Info);
				*/
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_Authenticating CustomCredential: '{0}'", e.CustomCredential.ToString()), AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_CreatingCookie UserName: {0}", e.UserName.ToString()), AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_CreatingCookie Password: {0}", e.Password.ToString()), AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_CreatingCookie Authenticated: {0}", e.Authenticated), AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_CreatingCookie AuthenticationIsComplete: {0}", e.AuthenticationIsComplete), AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( "[V]Global AuthenticationService_Authenticating END *******************************************************************", AuthenticationTrace.Sw.Info);
			}
			/* msdn sample
			string studentid    = String.Empty;
			string answer       = String.Empty;

			string[] credentials = e.CustomCredential.Split(new char[] { ',' });
			if (credentials.Length > 0)
			{
				studentid = credentials[0];
				if (credentials.Length > 1)
				{
					answer = credentials[1];
				}
			}

			try
			{
				e.Authenticated =
					StudentAuthentication.ValidateStudentCredentials(e.UserName, e.Password, studentid, answer);
			}
			catch (ArgumentNullException ex)
			{
				e.Authenticated = false;
			}

			e.AuthenticationIsComplete = true;
			 * */
		}

		void AuthenticationService_CreatingCookie(object sender, 
			System.Web.ApplicationServices.CreatingCookieEventArgs e)
		{
			if (AuthenticationTrace.Sw.TraceVerbose)
			{
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_CreatingCookie BEG Request.IsAuthenticated: {0}", Context.Request.IsAuthenticated), AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_CreatingCookie AuthenticationType: {0}", Context.Request.LogonUserIdentity.AuthenticationType), AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_CreatingCookie IsAnonymous: {0}", Context.Request.LogonUserIdentity.IsAnonymous), AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AuthenticationService_CreatingCookie e.UserName: {0}", e.UserName.ToString()), AuthenticationTrace.Sw.Info);
			}
			/* msdn sample
			FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
					(1,
					 e.UserName,
					 DateTime.Now,
					 DateTime.Now.AddMinutes(30),
					 e.IsPersistent,
					 e.CustomCredential,
					 FormsAuthentication.FormsCookiePath);

			string encryptedTicket =    FormsAuthentication.Encrypt(ticket);

			HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket);
			cookie.Expires = DateTime.Now.AddMinutes(30);

			HttpContext.Current.Response.Cookies.Add(cookie);
			e.CookieIsSet = true;
			 * */
		}

		#endregion methods dedicated to web services authentication

		#region Authentication

		/// <summary>
		/// Used when Forms authentication is on in Web.config, called before Application_AuthenticateRequest
		/// If a cookie exists, it is used to give access
		/// If user is coming from internal network, ie with an authenticated logonUserId, we try to auto authenticate creating a cookie
		/// </summary>
		public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
		{
			if ( DoNotLoadPortal )
				return;
			if (AuthenticationTrace.Sw.TraceVerbose)
			{
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global FormsAuthentication_OnAuthenticate Request.IsAuthenticated: {0}", Context.Request.IsAuthenticated), AuthenticationTrace.Sw.Info);
				if ( !InitApplication.IsIIS7_IP )
				{
					Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Global FormsAuthentication_OnAuthenticate LogonUserIdentity null: {0}.",Request.LogonUserIdentity == null),AuthenticationTrace.Sw.Info);
					try
					{
						Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Global FormsAuthentication_OnAuthenticate Request.LogonUserIdentity.IsAuthenticated: {0}",
															Context.Request.LogonUserIdentity.IsAuthenticated),AuthenticationTrace.Sw.Info);
						Trace2.WriteLine(
							string.Format("[V]Global FormsAuthentication_OnAuthenticate User: {0}, Name: {1}",
															Request.LogonUserIdentity.User,
															Request.LogonUserIdentity.Name),AuthenticationTrace.Sw.Info);
						Trace2.WriteLine(
							string.Format("[V]Global FormsAuthentication_OnAuthenticate AccountDomainSid: {0}, IsAccountSid: {1}",
															Request.LogonUserIdentity.User.AccountDomainSid,
															Request.LogonUserIdentity.User.IsAccountSid()),AuthenticationTrace.Sw.Info);
						Trace2.WriteLine(
							string.Format("[V]Global FormsAuthentication_OnAuthenticate AuthenticationType: {0}, ImpersonationLevel: {1}",
															Request.LogonUserIdentity.AuthenticationType,
															Request.LogonUserIdentity.ImpersonationLevel),AuthenticationTrace.Sw.Info);
						Trace2.WriteLine(
							string.Format("[V]Global FormsAuthentication_OnAuthenticate IsAnonymous: {0}, IsGuest: {1}, IsSystem: {2}",
															Request.LogonUserIdentity.IsAnonymous,
															Request.LogonUserIdentity.IsGuest,
															Request.LogonUserIdentity.IsSystem),AuthenticationTrace.Sw.Info);
						Trace2.WriteLine(
							string.Format("[V]Global FormsAuthentication_OnAuthenticate Owner: {0}, Token: {1}",
															Request.LogonUserIdentity.Owner,
															Request.LogonUserIdentity.Token),AuthenticationTrace.Sw.Info);
					}
					catch ( Exception ex1 )
					{
						Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Global FormsAuthentication_OnAuthenticate Tracing ex1: {0}",ex1),AuthenticationTrace.Sw.Info);
					}
					Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]Global FormsAuthentication_OnAuthenticate Context.User is null: {0}",Context.User == null),AuthenticationTrace.Sw.Info);
				}
			}
			if (!FormsAuthentication.CookiesSupported)
			{
				string msg  =   string.Format("[E]Global FormsAuthentication_OnAuthenticate Cookies not Supported Crawler: {0}, IsMobileDevice: {1}, UserAgent: {2}, UserHostAddress: {3}", 
						new object[]{Request.Browser.Crawler,Request.Browser.IsMobileDevice,Request.UserAgent,Request.UserHostAddress});
				if ( AuthenticationTrace.Sw.TraceError )
					Trace2.WriteLine(msg,AuthenticationTrace.Sw.Info);
				// Allows robots to continue
				if ( Request.Browser.Crawler )
					return;
				throw new CookieLessException(msg);
			}
			if ( ( args.User != null ) && ( args.User is ADNCRMPrincipal ) )
			{
				if (AuthenticationTrace.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global FormsAuthentication_OnAuthenticate already ADNCRMPrincipal name: {0}", args.User.Identity.Name),AuthenticationTrace.Sw.Info);
				return;
			}
			HttpCookie cok              =   Request.Cookies[FormsAuthentication.FormsCookieName];
			if ( cok == null ) 
			{
				if (AuthenticationTrace.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global FormsAuthentication_OnAuthenticate no cookie found with name : {0}, LogonUserIdentity.IsAuthenticated: {1}", 
						FormsAuthentication.FormsCookieName,Request.LogonUserIdentity.IsAuthenticated),AuthenticationTrace.Sw.Info);
				bool found              =   false;
				// This works only in IIS6 because from IIS7 we can't do the trick of site with Form authentication and Windows authentication(without anonymous) running on same site
				// 08/09 -> find something to do this in IIS7
				// User comes from internal network, and is domain identified, we try to authenticate him directly
				// finding/creating its account in provider
				if ( Request.LogonUserIdentity.IsAuthenticated && !string.IsNullOrEmpty(Request.LogonUserIdentity.AuthenticationType) )
				{
					found               =   ((AddonNiceMembershipProvider)Membership.Provider).AutoLogCrmUser(args,true);
				}
				if (AuthenticationTrace.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global FormsAuthentication_OnAuthenticate User found: {0}",found),AuthenticationTrace.Sw.Info);
				if ( !found )
					return;
			}
			else
			{
				if (AuthenticationTrace.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global FormsAuthentication_OnAuthenticate cookie found Expires: {0}", cok.Expires),AuthenticationTrace.Sw.Info);
				// If user come from internal network, and is domain identified, check cookie name
				// if different, we must try to authentify the actual user and not the one in cookie
				if ( !InitApplication.IsIIS7_IP && Request.LogonUserIdentity.IsAuthenticated && !string.IsNullOrEmpty(Request.LogonUserIdentity.AuthenticationType) )
				{
					string nm           =   PortalSecurity.UserNameFromCookie(cok);
					if (AuthenticationTrace.Sw.TraceVerbose)
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global FormsAuthentication_OnAuthenticate UserNameFromCookie: '{0}', LogonUserIdentity.Name: '{1}'.",
							nm,Request.LogonUserIdentity.Name),AuthenticationTrace.Sw.Info);
					if ( nm != Request.LogonUserIdentity.Name )
					{
						// remove bad ticket before adding new one
						Request.Cookies.Remove(cok.Name);
						// we try to find in Crm and generated a cookie
						( (AddonNiceMembershipProvider)Membership.Provider ).AutoLogCrmUser(args,true);
					}
				}
			}
			// we test this cookie to see if it contains our data , if nok we recreate our data from Membership data valid because we are authenticated
			try
			{
				PortalSecurity.OnFormAuthenticate(args);
			}
			catch (Exception e)
			{
				// Decrypt method failed.
				if ( AuthenticationTrace.Sw.TraceError )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Global FormsAuthentication_OnAuthenticate ex: {0}", e),AuthenticationTrace.Sw.Info);
				throw;
			}
		}

		/// <summary>
		/// Used when Windows authentication is on in Web.config
		/// </summary>
		public void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs args)
		{
			if ( DoNotLoadPortal )
			{
				/*
				if (AuthenticationTrace.Sw.TraceVerbose)
				{
					string _rawUrl = Context.Request.RawUrl.ToLower(CultureInfo.InvariantCulture);
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global WindowsAuthentication_OnAuthenticate exiting _rawUrl: {0}", _rawUrl), AuthenticationTrace.Sw.Info);
				}*/
				return;
			}
			if (AuthenticationTrace.Sw.TraceVerbose)
			{
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global WindowsAuthentication_OnAuthenticate BEG Request.IsAuthenticated: {0}", Context.Request.IsAuthenticated), AuthenticationTrace.Sw.Info);
				/* Pb IIS7
				try
				{
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global WindowsAuthentication_OnAuthenticate Request.LogonUserIdentity.IsAuthenticated: {0}",Context.Request.LogonUserIdentity.IsAuthenticated),AuthenticationTrace.Sw.Info);
				}
				catch(Exception ex1)
				{
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global WindowsAuthentication_OnAuthenticate Tracing ex1: {0}",ex1),AuthenticationTrace.Sw.Info);
				}
				 **/
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global WindowsAuthentication_OnAuthenticate args.Identity.IsAnonymous: {0}", args.Identity.IsAnonymous), AuthenticationTrace.Sw.Info);
			}
			if (!args.Identity.IsAnonymous && ( (args.User == null ) || !(args.User is ADNCRMPrincipal) ) )
			{
				if (AuthenticationTrace.Sw.TraceVerbose)
				{
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global WindowsAuthentication_OnAuthenticate args.Identity.Name: {0}", args.Identity.Name), AuthenticationTrace.Sw.Info);
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global WindowsAuthentication_OnAuthenticate args.User null: {0}", args.User == null), AuthenticationTrace.Sw.Info);
				}
				AddonNiceIdentity AdId	=	new AddonNiceIdentity(args.Identity);
				if (AuthenticationTrace.Sw.TraceVerbose)
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global WindowsAuthentication_OnAuthenticate setting AdId: {0}",AdId),AuthenticationTrace.Sw.Info);
				args.User			    =	new ADNCRMPrincipal(AdId,new string[0]);
			}
		}

		/// <summary>
		/// If the client is authenticated with the application, then replace the "User" intrinsic
		/// with a custom IPrincipal security object 
		/// </summary>
		protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
		{
			if ( DoNotLoadPortal )
			{
				if (AuthenticationTrace.Sw.TraceVerbose)
				{
					string _rawUrl          =   Context.Request.RawUrl.ToLower(CultureInfo.InvariantCulture);
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_AuthenticateRequest exiting _rawUrl: {0}", _rawUrl), AuthenticationTrace.Sw.Info);
				}
				return;
			}
			if (AuthenticationTrace.Sw.TraceVerbose)
			{
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_AuthenticateRequest BEG Request.IsAuthenticated: {0}", Context.Request.IsAuthenticated), AuthenticationTrace.Sw.Info);
				/* Pb IIS7
				try
				{
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_AuthenticateRequest AuthenticationType: {0}", Context.Request.LogonUserIdentity.AuthenticationType), AuthenticationTrace.Sw.Info);
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_AuthenticateRequest LogonUserIdentity.IsAnonymous: {0}", Context.Request.LogonUserIdentity.IsAnonymous), AuthenticationTrace.Sw.Info);
				}
				catch(Exception ex1)
				{
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_AuthenticateRequest Tracing ex1: {0}",ex1),AuthenticationTrace.Sw.Info);
				}
				*/
			}
			object objptl           =   Context.Items[StStr.strPortalSettings];
			if ( objptl == null )
			{
				string _rawUrl      =   Context.Request.RawUrl.ToLower(CultureInfo.InvariantCulture);
				string msg          =   string.Format("[E]Global Application_AuthenticateRequest no PortalSettings in context, _rawUrl: {0}", _rawUrl);
				if (AuthenticationTrace.Sw.TraceError)
					Trace2.WriteLine( msg, AuthenticationTrace.Sw.Info);
				throw new Exception(msg);
			}


			// Obtain PortalSettings from Current Context
			PortalSettings portalSettings			        =   (PortalSettings)objptl;
			if ( Context.Request.IsAuthenticated) // authenticated user we log every info
			{
				// We need to put our specific user in the context
				if ( Context.User != null )
				{
					bool isInternalPrinc                    =   Context.User is ADNCRMPrincipal;
					if ( AuthenticationTrace.Sw.TraceVerbose )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_AuthenticateRequest User is ADNCRMPrincipal: {0}", isInternalPrinc),AuthenticationTrace.Sw.Info);
					if (!isInternalPrinc )
					{
						AddonNiceIdentity AdId              =   Context.User.Identity as AddonNiceIdentity;
						if ( AuthenticationTrace.Sw.TraceVerbose )
							Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_AuthenticateRequest Identity is AddonNiceIdentity: {0}", AdId != null ),AuthenticationTrace.Sw.Info);
						if ( AdId == null )
							AdId                            =   new AddonNiceIdentity(Context.User.Identity);
						if ( AuthenticationTrace.Sw.TraceVerbose )
							Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_AuthenticateRequest setting ADNCRMPrincipal: {0}", AdId),AuthenticationTrace.Sw.Info);
						Context.User                        =   new ADNCRMPrincipal(AdId, null);
					}
				}
			}
			// if windows management is used , we need to get a unique id for user 
			// CSU 9/7 TBD replace with profile
			if ( !Context.Request.IsAuthenticated && Config.WindowMgmtControls)
			{
				// Need a uid, even for annoymous users
				// cookie bag
				IWebBagHolder abag									=	BagFactory.instance.create(BagFactory.BagFactoryType.CookieType);
				// user data already set
				string annoyUser									=	(string)abag[StStr.UserWinMgmtIndex];
				// if no cookie then let's get one
				if (annoyUser == null)
				{
					// new uid for window mgmt
					// save the data into a cookie bag
					abag[StStr.UserWinMgmtIndex]	                = Guid.NewGuid().ToString();
				}
			}
			if ( AuthenticationTrace.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_AuthenticateRequest END Request.IsAuthenticated: {0}.",Context.Request.IsAuthenticated),AuthenticationTrace.Sw.Info);
		} 

		
		/// <summary>
		/// The requested url doesn't necessitate more computing
		/// </summary>
		bool DoNotLoadPortal
		{
			get
			{
				string _rawUrl  =   Context.Request.RawUrl.ToLower(CultureInfo.InvariantCulture);
				string _rawUrl1 =   _rawUrl;
				int idx         =   _rawUrl.IndexOf('?');
				if ( idx > 0 )
					_rawUrl     =   _rawUrl.Substring(0,idx);
				// We need portalSettings for magic urls
				if ( _rawUrl.IndexOf("magicerror.aspx") > 0 )
					return false;
				if (_rawUrl.EndsWith(".css") ||
					_rawUrl.EndsWith(".js") ||
					_rawUrl.EndsWith(".jpg") ||
					_rawUrl.EndsWith(".png") ||
					_rawUrl.EndsWith(".gif") ||
					_rawUrl.IndexOf(".axd") > 0 ||
					( (_rawUrl1.IndexOf("radurid=") > 0 ) && (_rawUrl.IndexOf("/setup/update.aspx") > -1 )) || // telerik RadUploadProgressHandler marker and update
					_rawUrl.IndexOf("smarterror.aspx") > 0 ||
					// keep loading portasettings _rawUrl.IndexOf("telerik.web.ui.dialoghandler.aspx") > 0 || // telerik editor
					_rawUrl.EndsWith("/setup/update.aspx"))
					return true;
				// We must do special processing for ashx because some of them need to load crm wrapper
				if ( _rawUrl.IndexOf(".ashx") > 0 )
				{
					string AllowedAshx  =   Config.AllowedAshx;
					string[] Ashx       =   AllowedAshx.Split(new char[] { ',' },StringSplitOptions.RemoveEmptyEntries);
					foreach ( string shx in Ashx )
					{
						if ( _rawUrl.IndexOf(shx) > -1 )
						{
							if ( GlobalTraceSwitch.Sw.TraceVerbose )
								Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global DoNotLoadPortal ashx handler allowed: {0}.",shx),GlobalTraceSwitch.Sw.Info);
							return false;
						}
					}

					return true;
				}
				return false;
			}
		}

		private string UrlEncodeRedirect(string url)
		{
			Encoding e =    null;
			if ( Request != null ) 
				e   =   Request.ContentEncoding;
			else
			{
				e   =   Response.ContentEncoding;
				if (e == null)
				{
					e = Encoding.Default;
				}
			}
			return HttpUtility.UrlEncode(url,e);
		}

 
		/// <summary>
		/// We start the CRM Wrapper even if not authenticated
		/// </summary>
		protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
		{
			if ( DoNotLoadPortal )
			{
				return;
			}
			if ( AuthenticationTrace.Sw.TraceVerbose )
			{
				Trace2.WriteLine( "[V]Global Application_PostAuthenticateRequest BEG.",AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_PostAuthenticateRequest Request.IsAuthenticated: {0}", Context.Request.IsAuthenticated), AuthenticationTrace.Sw.Info);
				if ( Context.Request.LogonUserIdentity != null )
				{
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_PostAuthenticateRequest LogonUserIdentity.AuthenticationType: {0}",Context.Request.LogonUserIdentity.AuthenticationType),AuthenticationTrace.Sw.Info);
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_PostAuthenticateRequest LogonUserIdentity.IsAnonymous: {0}",Context.Request.LogonUserIdentity.IsAnonymous),AuthenticationTrace.Sw.Info);
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_PostAuthenticateRequest LogonUserIdentity.Name: {0}",Context.Request.LogonUserIdentity.Name),AuthenticationTrace.Sw.Info);
				}
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_PostAuthenticateRequest AppRelativeCurrentExecutionFilePath: {0}", Context.Request.AppRelativeCurrentExecutionFilePath), AuthenticationTrace.Sw.Info);
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_PostAuthenticateRequest Context.User: {0}", Context.User), AuthenticationTrace.Sw.Info);
				if ( Context.User != null )
				{
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_PostAuthenticateRequest Context.User.Identity: {0}", Context.User.Identity), AuthenticationTrace.Sw.Info);
					if ( Context.User.Identity != null )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_PostAuthenticateRequest Context.User.Identity.Name: {0}", Context.User.Identity.Name ), AuthenticationTrace.Sw.Info);
				}
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_PostAuthenticateRequest RequestType: {0}", Context.Request.RequestType), AuthenticationTrace.Sw.Info);
			}
			// if Forms authentication we check access rights to current requested url, if not allowed we redirect to login form
			if ( Config.AuthenticationMode == AuthenticationMode.Forms )
			{
				if ( !UrlAuthorizationModule.CheckUrlAccessForPrincipal(HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath,
					HttpContext.Current.User,HttpContext.Current.Request.RequestType) )
				{
					string rawUrl           =   UrlEncodeRedirect(Context.Request.RawUrl);
					string UrlName          =   string.Empty;
					PortalSettings ps       =   (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];

					int newPagID            =   ps.CustomSettings[StStr.SiteDefaultLoginPage].ToInt();
					if ( newPagID == 0 ) // Not defined we get any string in Web.config
					{
						UrlName             =   FormsAuthentication.LoginUrl;
						if ( UrlName.IndexOf('?') > -1 )
							UrlName         =   String.Format("{0}&ReturnUrl={1}",UrlName,rawUrl);
					}
					else // get the default value from portalsettings
					{
						UrlName             =   HttpUrlBuilder.BuildUrlWithCustomAttributes(DynPageLoc.Login,newPagID,String.Format("ReturnUrl={0}",rawUrl));
					}

					if ( AuthenticationTrace.Sw.TraceVerbose )
						Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_PostAuthenticateRequest redirecting to FormsAuthentication.LoginUrl: {0}, Request.Url.AbsoluteUri: {1}.",
							UrlName,Request.Url.AbsoluteUri),AuthenticationTrace.Sw.Info);
					Response.Redirect(UrlName,false);
				}
			}

			// we start wrapper even if not authenticated
			bool started                    =   PortalSecurity.StartWrapper();
			if ( started )
			{
				AddonNiceUser aUser         =   new AddonNiceUser();
				aUser.SetCurrent();
			}
			if ( AuthenticationTrace.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global Application_PostAuthenticateRequesf END wrapper started: {0}",started ),AuthenticationTrace.Sw.Info);
		}


		/// <summary>
		/// We adapt the anonymous user name to "AddonNice_Anonymous_User_" + DateTime.Now.Ticks;
		/// This work only if anonymous identification is enabled in web config
		/// <system.web>
		///    <anonymousIdentification enabled="true" />
		///    <profile default....
		///    <properties>
		///    <add name='xxx' allowAnonymous='true' />
		///    </properties>
		/// </summary>
		public void AnonymousIdentification_OnCreate(Object sender, AnonymousIdentificationEventArgs e)
		{
			if ( AuthenticationTrace.Sw.TraceVerbose )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AnonymousIdentification_OnCreate setting AnonymousID : {0}",e.AnonymousID ),AuthenticationTrace.Sw.Info);
			// Change the anonymous id
			e.AnonymousID   =   "AddonNice_Anonymous_User_" + DateTime.Now.Ticks;
			if (AuthenticationTrace.Sw.TraceVerbose)
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Global AnonymousIdentification_OnCreate setting AnonymousID : {0}",e.AnonymousID ),AuthenticationTrace.Sw.Info);
		}

		#endregion Authentication

		#region Application general Error handler

		/// <summary>
		/// General error handler for Application
		/// </summary>
		private void Application_Error(object sender, System.EventArgs e)
		{
			Exception ex    =   Server.GetLastError();
			if (ex != null)
			{
				if ( GlobalTraceSwitch.Sw.TraceError )
					Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Global Application_Error ex : {0}", ex),GlobalTraceSwitch.Sw.Info);
				ErrorHandler.ProcessUnhandledException();
				if ( GlobalTraceSwitch.Sw.TraceError )
					Trace2.WriteLine("[E]Global Application_Error END.",GlobalTraceSwitch.Sw.Info);
				return;
			}
			if ( GlobalTraceSwitch.Sw.TraceError )
				Trace2.WriteLine("[E]Global Application_Error END with No LastError",GlobalTraceSwitch.Sw.Info);
		}

		#endregion Application general Error handler

		#region Start / End Application

		void Application_Start()
		{
			if ( InitApp == null )
				InitApp	=	new InitApplication();
			InitApp.Start();
		}
		

		/// <summary>
		/// We trace end of application
		/// </summary>
		public void Application_OnEnd()
		{
			if ( GlobalTraceSwitch.Sw.TraceInfo )
				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[I]Application end at : {0}",DateTime.UtcNow.ToLongTimeString()),GlobalTraceSwitch.Sw.Info);
		}

		#endregion Start / End Application
	}
}